import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import styles from '@/components/common/PateoTable/TableList.less';
import { Card, Button, Switch,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddModal from './addModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import PropTypes from 'prop-types';

const mapStateToProps = (state: any) => ({
  goodType: state.goodType,
  loading: state.loading.effects['goodType/postFetchPage'],
  menu:state.menu,
});

class GoodType extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any
  };
  state = {
    addVisible: false,
    isAdd:true,
    record:{},
    formValues: {},
    pagination: {
      current: 1,
      pageSize: 10,
    },
  };
  searchRef = React.createRef();

  componentDidMount() {
   this.handleFlushPage();
  }
 
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'goodType/initData',
    });
  }
  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues,pagination } = this.state;
    dispatch({
      type: 'goodType/postFetchPage',
      payload: { url: '/optshop/base/goodstype/search', ...formValues,...pagination, },
    });
  };
  //新增
  handleAdd=()=>{
    this.setState({
        addVisible: true,
        isAdd:true,
      });
  }
  closeAddModal = () => {
    this.setState({
      addVisible: false,
      record: {}
    });
    this.handleFlushPage();
  };
  handleEdit = (record:any) =>{
    this.setState({
        addVisible: true,
        isAdd:false,
        record:record,
      });
  }
   //删除
   handleDeleteDate=(record:any)=>{
     const { dispatch} = this.props;
     dispatch({
       type: 'goodType/getData',
       payload: {
         url: '/optshop/base/goodstype/delete',
         sid: record.sid,
       },
       callback: (response: any) => {
         if (response.statusCode === '0') {
               message.success('删除成功！') ;
           this.handleFlushPage();
         }
       },
     });
   }
   onSwitchChange=(values:any, record:any)=>{
   //使用编辑接口变更状态
   const { dispatch,} = this.props;
   const params = {
     ...record,
     isShow: values? 1 : 0,
   }
   dispatch({
     type: 'goodType/postObjWithRes',
     payload: {
       url: '/optshop/base/goodstype/update',
       ...params
     },
     callback: (response: any) => {
       if (response.statusCode === '0') {
        message.success('变更成功！');
        this.handleFlushPage();
       }
     },
   });
   }
   handleFormReset = () => {
    this.searchForm.current.setFieldsValue({});
    this.setState({
      formValues: {},
      pagination: {
        current: 1,
        pageSize: 10,
      },
    });
  };
  render() {
    const { addVisible,isAdd,record, formValues} = this.state;
    const {
      goodType: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { menu: { permissions }} = this.props;
    const isAddAuth = permissions.includes('/goodsManager/goodType/goodType_doAdd');
    const isChangeShowAuth = permissions.includes('/goodsManager/goodType/goodType_doChangeShow');
    const searchItems = [
      {
        type: 'input',
        title: `类型名称`,
        key: 'goodsTypeName',
      },
      {
        type: 'input',
        title: `类型编码`,
        key: 'goodsTypeId',
      },
    ];

    const columns = [
      {
        title: `品牌`,
        dataIndex: 'brandName',
      },
      {
        title: `商品类型名称`,
        dataIndex: 'goodsTypeName',
      },
      {
        title: `商品类型编码`,
        dataIndex: 'goodsTypeId',
      },
      {
        title: `是否显示`,
        dataIndex: 'isShow',
        render: (text:any, record:any)=>{
         return (
           <Switch checked={text == 1 ? true  : false} onChange={(checked)=>this.onSwitchChange(checked,record)} disabled={!isChangeShowAuth}/>
                );
        }
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: `创建时间`,
        dataIndex: 'createTime',
      },
      {
        title: `修改人`,
        dataIndex: 'updateBy',
      },
      {
        title: `修改时间`,
        dataIndex: 'updateTime',
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 100,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'goodType_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'goodType_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleDeleteDate(record),
            }
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{!pagination ? 0 : pagination.total}&nbsp;条</span>,
    };
    const tableProps = {
      columns:columns,
      dataSource: [...(list || [])],
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    return (
      <div>
        <Card>
        <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'goodType/postFetchPage', url: '/optshop/base/goodstype/search' }}
            aveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={(val: any) => {
              const { pagination } = this.state;
              return {
                ...val,
                ...pagination,
              };
            }}
          />
        </Card>
        <Card className={styles.standardTable}>
          {isAddAuth && (
        <div style={{marginBottom: '10px'}}>
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => this.handleAdd()}
          >
            新增
          </Button>
          </div>
          )}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'goodType/postFetchPage', url: '/optshop/base/goodstype/search' }}
            formValues={formValues}
          />
        </Card>
        <AddModal
          modalVisible={addVisible}
          closeModal={this.closeAddModal}
          isAdd={isAdd}
          record={record}
        />
      </div>
    );
  }
}

export default connect(mapStateToProps)(GoodType);
